<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="id ? '编辑月卡': '增加月卡' " @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form ref="carMonthForm" label-width="100px" :model="carMonthForm" :rules="carMonthRules">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carMonthForm.personName" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carMonthForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carMonthForm.carNumber" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carMonthForm.carBrand" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <el-form ref="feeForm" :model="feeForm" :rules="feeFormRules" label-width="100px">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>

        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button :disabled="isEdit" @click="confirmClear">重置</el-button>
        <el-button :disabled="isEdit" type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { addCardMonthAPI, showCardMonthAPI, editCardMonthAPI } from '@/api/carCard'
export default {
  name: 'AddCardmonth',
  data() {
    return {
      carMonthForm: {
        personName: '',
        phoneNumber: '',
        carNumber: '',
        carBrand: ''
      },
      carMonthRules: {
        personName: [
          {
            required: true, message: '请输入车主姓名', trigger: 'blur'
          }
        ],
        phoneNumber: [
          {
            required: true, message: '请输入联系方式', trigger: 'blur'
          },
          {
            pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', tigger: 'blur'
          }
        ],
        carNumber: [
          {
            required: true, message: '请输入车辆号码', trigger: 'blur'
          },
          // 自定义校验，不用配置message
          {
            validator: this.validatorCarNumber, trigger: 'blur'
          }
        ],
        carBrand: [
          {
            required: true, message: '请输入车辆品牌', trigger: 'blur'
          }
        ]
      },
      feeForm: {
        payTime: '', // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: '' // 支付方式
      },
      // 缴费规则
      feeFormRules: {
        payTime: [
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ]
      },
      // 支付方式列表
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '线下'
        }
      ],
      isEdit: false // 是否为编辑状态，根据id参数决定

    }
  },
  computed: {
    // 将id封装为计算属性，以后每次使用id时都不需要再写太长
    id() {
      return this.$route.query.id
    }
  },
  created() {
    if (this.id) {
      this.showCardMonth()
    }
  },
  methods: {
    validatorCarNumber(rule, value, callback) {
      // rule: 用不到
      // value: 用户输入的数据
      // callback: 不管成功还是失败都要进行调用，成功：callback()  失败：callback(new Error(错误信息))
      const plateNumberRegex = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/
      if (plateNumberRegex.test(value)) {
        callback()
      } else {
        callback(new Error('请输入正确的车牌号'))
      }
    },
    // 编辑或新增时确认提交表单，使用Promise实现表单验证后的异步提交操作
    confirmAdd() {
      this.$refs.carMonthForm.validate(flag => {
        if (flag) {
          this.$refs.feeForm.validate(async(flag) => {
            if (flag) {
              // 将上述两个表单中的数据合并到新的数组中
              const requestData = {
                ...this.carMonthForm,
                ...this.feeForm,
                cardStartDate: this.feeForm.payTime[0],
                cardEndDate: this.feeForm.payTime[1]
              }
              // 由于接口做了校验，多字段不行，所以提交之前要把多余的字段删掉
              delete requestData.payTime
              // 此处由于公用一个表单，所以要进行判断，如果有id就调用编辑月卡的函数，如果没id就调用添加月卡的函数
              if (this.id) {
                await editCardMonthAPI(requestData)
                this.$message.success('月卡信息修改成功')
              } else {
                await addCardMonthAPI(requestData)
                this.$message.success('月卡信息添加成功')
              }
              this.$router.back()
            }
          })
        }
      })
    },
    // 清空表单域
    confirmClear() {
      // 只能清空加了prop的表单域
      this.$refs.feeForm.resetFields()
      this.$refs.carMonthForm.resetFields()
    },
    // 回显表单数据
    async showCardMonth() {
      // this.isEdit = true
      // 根据id获取数据，并将其赋值给数组进行赋值
      const { data: { personName, phoneNumber, carNumber, carBrand, cardStartDate, cardEndDate, paymentAmount, paymentMethod, carInfoId, rechargeId }} =
       await showCardMonthAPI(this.id)
      this.carMonthForm = { personName, phoneNumber, carNumber, carBrand, carInfoId }
      this.feeForm = {
        payTime: [cardStartDate, cardEndDate],
        paymentAmount,
        paymentMethod,
        rechargeId
      }
    }
  }
}
</script>

  <style scoped lang="scss">
  .add-card {
    background-color: #f4f6f8;
    height: 100vh;

    .add-header {
      display: flex;
      align-items: center;
      padding: 0 20px;
      height: 64px;
      background-color: #fff;

      .left {
        span {
          margin-right: 4px;
        }
        .arrow{
          cursor: pointer;
        }
      }

      .right {
        text-align: right;
      }
    }

    .add-main {
      background: #f4f6f8;
      padding: 20px 130px;

      .form-container {
        background-color: #fff;

        .title {
          height: 60px;
          line-height: 60px;
          padding-left: 20px;
        }

        .form {
          margin-bottom: 20px;
          padding: 20px 65px 24px;

          .el-form {
            display: flex;
            flex-wrap: wrap;

            .el-form-item {
              width: 50%;
            }
          }
        }
      }
      .preview{
        img{
          width: 100px;
        }
      }
    }

    .add-footer {
      position: fixed;
      bottom: 0;
      width: 100%;
      padding: 24px 50px;
      color: #000000d9;
      font-size: 14px;
      background: #fff;
      text-align: center;
    }
  }
  </style>
